<template>
  <div>

    <hr style="border: none">
    <div>
      <el-button size="mini" type="primary" @click="showEditForm('add')" icon="el-icon-plus">添加</el-button>
      <hr style="border: none">
      <el-form :inline="true" :model="queryForm.data" class="demo-form-inline">
        <el-form-item>
          <el-select v-model="queryForm.data.domainId" placeholder="所属域">
            <el-option
              v-for="item in options.domainId"
              :key="item.id"
              :label="item.text"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-input v-model="queryForm.data.name" placeholder="名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="queryFormSubmit" icon="el-icon-search">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <hr>
    <div>
      <el-table :data="tableData" v-loading="loading" style="width: 100%">
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="name"></el-table-column>
        <el-table-column label="角色代码" prop="enname"></el-table-column>
        <el-table-column label="操作" fixed="right" width="600" prop="id">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="showUserPanel(scope.$index, scope.row)"
                       icon="el-icon-edit">用户管理
            </el-button>
            <el-button size="mini" type="primary" @click="showPrivilegePanel(scope.$index, scope.row)"
                       icon="el-icon-edit">权限管理
            </el-button>
            <el-button size="mini" type="primary" @click="showEditForm('edit',scope.$index, scope.row)"
                       icon="el-icon-edit">编辑
            </el-button>
            <el-button size="mini" type="danger" @click="deleteItem(scope.$index, scope.row)"
                       icon="el-icon-delete">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page="pages.currentPage" :page-sizes="pages.pageSizeList"
                     :page-size="pages.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pages.total"
                     prev-text="上一页"
                     next-text="下一页" background>
      </el-pagination>
    </div>
    <div>
      <el-dialog :title="editForm.formName" :visible.sync="editForm.dialogFormVisible">
        <el-form ref="editForm.data" :model="editForm.data" :rules="editForm.rules" label-width="120px"
                 label-position="right">

          <el-row>
            <el-col :span="12">
              <el-form-item label="所属域" prop="domainId">
                <el-select v-model="editForm.data.domainId" placeholder="请选择" style="width: 100%">
                  <el-option
                    v-for="item in options.domainId"
                    :key="item.id"
                    :label="item.text"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="角色代码" prop="enname">
                <el-input v-model="editForm.data.enname" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="角色名称" prop="name">
                <el-input v-model="editForm.data.name" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <input type="hidden" v-model="editForm.data.id">
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editForm.dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="save('editForm.data')">保 存</el-button>
        </div>
      </el-dialog>
      <el-dialog :title="userPanel.title" :visible.sync="userPanel.visible">
        <el-transfer
          v-model="userPanel.rightData"
          :data="userPanel.leftData"
          :props="{key: 'id',label: 'text'}"
          :titles="['未选择', '已选择']"></el-transfer>
        <div slot="footer" class="dialog-footer">
          <el-button @click="userPanel.visible = false">取 消</el-button>
          <el-button type="primary" @click="saveUserPanel()">保 存</el-button>
        </div>
      </el-dialog>
      <el-dialog :title="privilegePanel.title" :visible.sync="privilegePanel.visible">
        <el-tree :data="privilegePanel.all"
                 :props="privilegePanel.treeProps" node-key="id" show-checkbox ref="tree"
                 :default-expanded-keys="privilegePanel.selected"
                 :default-checked-keys="privilegePanel.selected"></el-tree>
        <div slot="footer" class="dialog-footer">
          <el-button @click="privilegePanel.visible = false">取 消</el-button>
          <el-button type="primary" @click="savePrivilegePanel()">保 存</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  export default {
    data () {
      return {
        loading: false,
        url: {
          queryPage: '/datacenter/com/lizhivscaomei/jes/sys/controller/sysRole/query/page',
          save: '/datacenter/com/lizhivscaomei/jes/sys/controller/sysRole/save',
          delete: '/datacenter/com/lizhivscaomei/jes/sys/controller/sysRole/delete',
          detail: '/datacenter/com/lizhivscaomei/jes/sys/controller/sysRole/query/detail',
          domainOptions: '/datacenter/com/lizhivscaomei/jes/sys/controller/sysDomain/query/spinner',
          roleUserQuery: '/datacenter/com/lizhivscaomei/jes/sys/controller/sysRole/user/query',
          roleUserSave: '/datacenter/com/lizhivscaomei/jes/sys/controller/sysRole/user/save',
          rolePrivilegeQuery: '/datacenter/com/lizhivscaomei/jes/sys/controller/sysRole/privilege/query',
          rolePrivilegeSave: '/datacenter/com/lizhivscaomei/jes/sys/controller/sysRole/privilege/save'
        },
        pages: {
          total: 0,
          currentPage: 1,
          pageSize: 20,
          pageSizeList: [20, 40, 100]
        },
        tableData: [],
        editForm: {
          formName: 'SysRole',
          dialogFormVisible: false,
          data: {
            domainId: '',
            enname: '',
            name: '',
            id: ''
          },
          rules: {
            domainId: [{required: true, message: '请输入所属域', trigger: 'blur'}],
            enname: [{required: true, message: '请输入角色代码', trigger: 'blur'}],
            name: [{required: true, message: '请输入角色名称', trigger: 'blur'}]
          }
        },
        queryForm: {
          dialogFormVisible: false,
          data: {
            currentPage: 1,
            pageSize: 10,

            domainId: '',

            enname: '',

            name: ''

          }
        },
        options: {
          domainId: []
        },
        userPanel: {
          title: '角色-用户',
          visible: false,
          roleId: '',
          leftData: [],
          rightData: []
        },
        privilegePanel: {
          title: '角色-权限',
          roleId: '',
          visible: false,
          treeProps: {
            value: 'id',
            label: 'text',
            children: 'nodes'
          },
          all: [],
          selected: []
        }
      }
    },
    methods: {
      handleSizeChange: function (val) {
        this.queryFormSubmit()
      },
      handleCurrentChange: function (val) {
        this.queryFormSubmit()
      },
      queryFormSubmit: function () {
        this.loading = true
        this.queryForm.data.currentPage = this.pages.currentPage
        this.queryForm.data.pageSize = this.pages.pageSize
        this.$http.get(this.$http.adornUrl(this.url.queryPage), {params: this.queryForm.data}).then((res) => {
          this.loading = false
          if (res.data.success) {
            this.tableData = res.data.data.list
            this.pages.total = res.data.data.total
          } else {
            this.$message({
              type: 'error',
              message: res.data.info
            })
          }
        }, (res) => {
          this.loading = false
          this.$message({
            showClose: true,
            message: '网络错误,code=' + res.status,
            type: 'error'
          })
        })
      },
      showEditForm: function (action, index, row) {
        if (action === 'add') {
          this.editForm.data.id = ''
        }
        if (action === 'edit') {
          this.editForm.data.id = row.id
          this.editForm.data.name = row.name
          this.editForm.data.enname = row.enname
          this.editForm.data.domainId = row.domainId
        }
        this.editForm.dialogFormVisible = true
      },
      deleteItem: function (index, row) {
        this.$confirm('此操作将删除' + row.name + ', 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.get(this.$http.adornUrl(this.url.delete), {params: {id: row.id}}).then((res) => {
            if (res.data.success) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.queryFormSubmit()
            } else {
              this.$message({
                type: 'error',
                message: res.data.info
              })
            }
          }, (res) => {
            this.$message({
              showClose: true,
              message: '网络错误' + res.status,
              type: 'error'
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      save: function (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$http({
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
              },
              url: this.$http.adornUrl(this.url.save),
              method: 'POST',
              data: this.$http.adornData(this.editForm.data, false, 'form')
            }).then((res) => {
              if (res.data.success) {
                this.$message({
                  type: 'success',
                  message: '保存成功!'
                })
                this.editForm.dialogFormVisible = false
                this.queryFormSubmit()
              } else {
                this.$message({
                  type: 'error',
                  message: res.data.info
                })
              }
            }, (res) => {
              this.loading = false
              console.log(res.status)
              this.$message({
                showClose: true,
                message: '网络错误' + res.status,
                type: 'error'
              })
            })
          } else {
            console.log('error submit!!')

            return false
          }
        })
      },
      showUserPanel: function (index, row) {
        this.userPanel.roleId = row.id
        this.$http.get(this.$http.adornUrl(this.url.roleUserQuery), {params: {roleId: this.userPanel.roleId}}).then((res) => {
          this.userPanel.leftData = res.data.data.all
          this.userPanel.rightData = res.data.data.selected
          this.userPanel.visible = true
        }, (res) => {
          this.$message({
            showClose: true,
            message: '网络错误' + res.status,
            type: 'error'
          })
        })
      },
      saveUserPanel: function () {
        this.$confirm('权限模块谨慎操作, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
            },
            url: this.$http.adornUrl(this.url.roleUserSave),
            method: 'POST',
            data: this.$http.adornData({
              roleId: this.userPanel.roleId,
              selectedList: this.userPanel.rightData.join(',')
            }, false, 'form')
          }).then((res) => {
            if (res.data.success) {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              this.userPanel.visible = false
            } else {
              this.$message({
                type: 'error',
                message: res.data.info
              })
            }
          }, (res) => {
            this.loading = false
            console.log(res.status)
            this.$message({
              showClose: true,
              message: '网络错误' + res.status,
              type: 'error'
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      },
      showPrivilegePanel: function (index, row) {
        this.privilegePanel.roleId = row.id
        this.$http.get(this.$http.adornUrl(this.url.rolePrivilegeQuery), {params: {roleId: this.privilegePanel.roleId}}).then((res) => {
          if (res.data.success) {
            this.privilegePanel.all = res.data.data.all
            this.privilegePanel.selected = res.data.data.selected
            this.privilegePanel.visible = true
          } else {
            this.$message({
              type: 'error',
              message: res.data.info
            })
          }
        }, (res) => {
          this.$message({
            showClose: true,
            message: '网络错误' + res.status,
            type: 'error'
          })
        })
      },
      savePrivilegePanel: function () {
        this.$confirm('权限模块谨慎操作, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var selectedIds = []
          var selectedNodes = this.$refs.tree.getCheckedNodes()
          for (var i = 0; i < selectedNodes.length; i++) {
            selectedIds.push(selectedNodes[i].id)
          }
          this.$http({
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
            },
            url: this.$http.adornUrl(this.url.rolePrivilegeSave),
            method: 'POST',
            data: this.$http.adornData({
              roleId: this.privilegePanel.roleId,
              selectedList: selectedIds.join(',')
            }, false, 'form')
          }).then((res) => {
            if (res.data.success) {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              this.privilegePanel.visible = false
            } else {
              this.$message({
                type: 'error',
                message: res.data.info
              })
            }
          }, (res) => {
            this.loading = false
            console.log(res.status)
            this.$message({
              showClose: true,
              message: '网络错误' + res.status,
              type: 'error'
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      }
    },
    mounted: function () {
      this.$http.get(this.$http.adornUrl(this.url.domainOptions)).then((res) => {
        if (res.data.success) {
          this.options.domainId = res.data.data
          this.editForm.data.domainId = res.data.data[0].id
          this.queryForm.data.domainId = res.data.data[0].id
          this.queryFormSubmit()
        } else {
          this.$message({
            type: 'error',
            message: res.data.info
          })
        }
      }, function (res) {
        this.$message({
          showClose: true,
          message: '网络错误,code=' + res.status,
          type: 'error'
        })
      })
    }
  }
</script>

<style scoped>

</style>
